package com.isxcode.link.plugin.service;

import com.isxcode.link.common.constant.FileConstants;
import com.isxcode.link.common.exception.LinkExceptionEnum;
import com.isxcode.link.common.pojo.dto.LinkData;
import com.isxcode.link.common.pojo.LinkRequest;
import com.isxcode.link.common.properties.LinkPluginProperties;
import com.isxcode.link.common.utils.CommandUtils;
import com.isxcode.link.common.exception.LinkException;
import com.isxcode.link.common.utils.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class LinkBizService {

    private final LinkPluginProperties linkPluginProperties;

    public LinkData execute(LinkRequest linkRequest) {

        String executeId = UUID.randomUUID().toString().replace("-", "");

        // 关键字检测
//        if (linkRequest.getSyncType() == null) {
//            throw new LinkException(LinkExceptionEnum.REQUEST_VALUE_EMPTY);
//        }

        // 生成sqoop执行命令
//        List<String> sqoopCommandList = new ArrayList<>();
//        switch (linkRequest.getSyncType()){
//            case IMPORT:
//                sqoopCommandList = new ArrayList<>(Arrays.asList(
//                    "sqoop", "import",
//                    "-Dorg.apache.sqoop.export.text.dump_data_on_error=true",
//                    "-Dorg.apache.sqoop.splitter.allow_text_splitter=true",
//                    "--verbose",
//                    "--driver", linkRequest.getJdbcDriver(),
//                    "--connect", linkRequest.getJdbcUrl(),
//                    "--username", linkRequest.getJdbcUsername(),
//                    "--password", linkRequest.getJdbcPassword(),
//                    "--split-by", linkRequest.getSplitBy(),
//                    "--target-dir", linkRequest.getTargetDir(),
//                    "--fields-terminated-by", "\"" + linkRequest.getFieldsTerminatedBy() + "\""));
//
//                // 用户自定义查询sql
//                if (!Strings.isEmpty(linkRequest.getQuerySql())) {
//                    sqoopCommandList.add("--query");
//                    if (linkRequest.getQuerySql().toLowerCase().contains("where")) {
//                        sqoopCommandList.add("\"" + linkRequest.getQuerySql() + " and \\$CONDITIONS\"");
//                    }else{
//                        sqoopCommandList.add("\"" + linkRequest.getQuerySql() + " where \\$CONDITIONS\"");
//                    }
//                }
//
//                break;
//            case EXPORT:
//                break;
//            default:
//        }

        // 插件
//        if (linkRequest.isAppend()) {
//            sqoopCommandList.add("--append");
//        }

        // 项目临时文件路径
        String tmpPath = linkPluginProperties.getTmpDir();

        // 创建${executeId}.sh文件
        String sqoopCommand = linkRequest.getCommand();
        String sqoopShPath = tmpPath + File.separator + executeId + FileConstants.SH_SUFFIX;
        FileUtils.StringToFile(sqoopCommand, sqoopShPath, StandardOpenOption.WRITE);

        // 创建日志文件
        String logPath = tmpPath + File.separator + executeId + FileConstants.LOG_SUFFIX;
        FileUtils.generateFile(logPath);

        // 运行日志
        String executeCommand = "bash " + sqoopShPath;
        log.debug(" 执行命令:" + executeCommand);
        try {
            CommandUtils.executeCommand(executeCommand, logPath);
        } catch (Exception e) {
            throw new LinkException(LinkExceptionEnum.COMMAND_EXECUTE_ERROR);
        }

        return LinkData.builder()
            .executeId(executeId)
            .build();
    }

    public LinkData getJobLog(LinkRequest linkRequest) {

        String logPath = linkPluginProperties.getTmpDir() + File.separator + linkRequest.getExecuteId() + FileConstants.LOG_SUFFIX;
        Path path = Paths.get(logPath);
        Resource resource;
        try {
            resource = new UrlResource(path.toUri());
            String logStr = new BufferedReader(new InputStreamReader(resource.getInputStream())).lines().collect(Collectors.joining("\n"));
            return LinkData.builder().log(logStr).build();
        } catch (IOException e) {
            log.debug("AcornBizService.getJobLog.getMessage" + e.getMessage());
            throw new LinkException(LinkExceptionEnum.READ_LOG_FILE_ERROR);
        }
    }

}
